package com.googlecode.openrtp.grizzly;

import java.util.Comparator;
import org.glassfish.grizzly.filterchain.Filter;
import com.googlecode.openrtp.spi.annotation.Priority;

/**
 *
 * @author jocke
 */
public class FilterPriorityComparator implements Comparator<Filter> {

    private static final FilterPriorityComparator INSTANCE = new FilterPriorityComparator();

    public static FilterPriorityComparator getInstance() {
        return INSTANCE;
    }

    @Override
    public int compare(Filter o1, Filter o2) {

        if (hasPriority(o1) && hasPriority(o2)) {
            return getValue(o1).compareTo(getValue(o2));

        } else if (hasPriority(o1) && !hasPriority(o2)) {
            return - 1;

        } else if (!hasPriority(o1) && hasPriority(o2)) {
            return 1;

        } else {
            return 0;
        }
    }

    private Integer getValue(Filter f) {
        return Integer.valueOf(f.getClass().getAnnotation(Priority.class).intValue());
    }

    private boolean hasPriority(Filter f) {
        return f.getClass().isAnnotationPresent(Priority.class);
    }
}
